'use strict'

import qiniu from 'qiniu'
import sha1 from 'sha1'
import uuid from 'uuid'
import Promise from 'bluebird'
import cloudinary from 'cloudinary'
import config from '../../config/config'

qiniu.conf.ACCESS_KEY = config.qiniu.AK
qiniu.conf.SECRET_KEY = config.qiniu.SK
cloudinary.config(config.cloudinary)


exports.getQiniuToken = body => {
  const type = body.type
  let key = uuid.v4()
  let putPolicy
  let options = {
    persistentNotifyUrl: config.notify
  }

  if (type === 'avatar') {
    key += '.jpeg'
    putPolicy = new qiniu.rs.PutPolicy(config.qiniu.bucket + ':' + key)


  }
  else if (type === 'video') {
    key += '.mp4'
    options.scope = 'rnappvideo:' + key
    options.persistentOps = 'avthumb/mp4/an/1'
    putPolicy = new qiniu.rs.PutPolicy2(options)
  }
  else if (type === 'audio') {
    // key += ''
  }

  const token = putPolicy.token()

  return {
    token,
    key
  }
}

exports.getCloudinaryToken = body => {
  const type = body.type
  const timestamp = body.timestamp
  let folder
  let tags

  if (type === 'avatar') {
    folder = 'avatar'
    tags = 'app,avatar'
  } else if (type === 'video') {
    folder = 'video'
    tags = 'app,video'
  } else if (type === 'audio') {
    folder = 'audio'
    tags = 'app,audio'
  }

  let signature = 'folder=' + folder + '&tags=' + tags + '&timestamp=' + timestamp + config.cloudinary.api_secret
  signature = sha1(signature)
  let key = uuid.v4()

  return {
    token: signature,
    key
  }
}

exports.uploadToCloudinary = url => {
  return new Promise((resolve, reject) => {
    cloudinary.uploader.upload(url, result => {
      if (result && result.public_id) {
        resolve(result)
      } else {
        reject(result)
      }
    }, {
        resource_type: 'video',
        folder: 'video'
      })
  })
}

exports.saveToQiniu = (url, key) => {
  const client = new qiniu.rs.Client()

  return new Promise((resolve, reject) => {
    client.fetch(url, 'rnappvideo', key, (err, ret) => {
      if (err)
        reject(err)
      else
        resolve(ret)
    })
  })
}
